package cn.com.dashihui.seller.controller;

import org.apache.commons.codec.binary.StringUtils;

import com.jfinal.aop.Clear;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

import cn.com.dashihui.seller.common.CommonCode;
import cn.com.dashihui.seller.common.ResultMap;

public class AppApiController extends BaseController {

	@Clear
	public void checkVersion(){
		String typeStr = getPara("TYPE");
    	String versionStr = getPara("VERSION");
    	if(StrKit.isBlank(typeStr)){
    		renderFailed("参数TYPE不能为空");
    		return;
    	}else if(!typeStr.equals("A")&&!typeStr.equals("B")){
    		renderFailed("参数TYPE不正确");
    		return;
    	}else if(StrKit.isBlank(versionStr)){
    		renderFailed("参数VERSION不能为空");
    		return;
    	}else if(!versionStr.matches("[1-9]{1,3}\\.\\d{1,3}\\.\\d{1,5}")){
    		renderFailed("参数VERSION格式不正确");
    		return;
    	}
    	
    	String downUrl = "";
    	String lastVersion = "";
    	String fileName = "";
    	if(StringUtils.equals(typeStr, CommonCode.Platform.android)){
    		lastVersion = PropKit.get("constants.android.version");
    		downUrl = PropKit.get("constants.urlpath")+"/app/apk/dashihui-seller"+lastVersion+".apk";
    		fileName = "dashihui-seller"+lastVersion+".apk";
    	} else if(StringUtils.equals(typeStr, CommonCode.Platform.iPhone)){
    		lastVersion = PropKit.get("constants.ios.version");
    		downUrl = PropKit.get("constants.ios.download");
    	}
    	if(StrKit.isBlank(downUrl) || StrKit.isBlank(lastVersion)){
    		renderFailed("未找到该设备类型");
    		return;
    	}
    	String[] versionArr = versionStr.split("\\.");
    	int iVersionPart1 = Integer.valueOf(versionArr[0]), iVersionPart2 = Integer.valueOf(versionArr[1]), iVersionPart3 = Integer.valueOf(versionArr[2]);
    	//查询指定平台客户端的最新版本信息
    	String[] lastVersionArr = lastVersion.split("\\.");
    	if(lastVersion!=null){
    		int lVersionPart1 = Integer.valueOf(lastVersionArr[0]), lVersionPart2 = Integer.valueOf(lastVersionArr[1]), lVersionPart3 = Integer.valueOf(lastVersionArr[2]);
    		//将数据库中的最新版本信息的版本号三个部分，与入参的版本号三个部分进行比较，判断数据库中的最新版本信息是否比入参版本号要大
    		if(lVersionPart1>iVersionPart1
    				||(lVersionPart1==iVersionPart1&&lVersionPart2>iVersionPart2)
    				||(lVersionPart1==iVersionPart1&&lVersionPart2==iVersionPart2&&lVersionPart3>iVersionPart3)){
    			ResultMap resultMap = ResultMap.newInstance()
    					.put("updateflg","B")
    					.put("curver", lastVersion)
    					.put("downurl", downUrl)
    					.put("fileName", fileName);
    			renderSuccess(resultMap.getAttrs());
    			return;
    		}
    	}
		renderSuccess(ResultMap.newInstance().put("UPDATEFLG","A"));
	}
	
	public void download() {
		String lastVersion = PropKit.get("constants.version");
		redirect("/app/apk/dashihui-seller"+lastVersion+".apk");
	}
}
